<template>
  <div class="ai-chat">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="back" @click="goBack">＜</div>
      <div class="title">快速问诊</div>
      <div class="notification-icon">🔔</div>
      <div class="notification">

      </div>
    </div>

    <!-- 聊天内容区域 -->
    <div class="chat-container" ref="chatContainer">
      <!-- AI欢迎消息 -->
      <div class="message ai-message">
        <div class="message-content">
          你好，请详细描述您的病情，我们将会安排适合的医生为你服务
        </div>
      </div>

      <!-- 快速选择按钮 -->
      <div class="quick-replies">
        <div class="quick-reply-hint">您也可以点击标签快速回答：</div>
        <!-- 快速回答标签组 - 这部分是从后端返回的数据 -->
        <div class="tags">
          <div
              v-for="tag in quickReplyTags"
              :key="tag.id"
              class="tag-item"
              @click="selectQuickReply(tag.symptomName)"
          >
            {{ tag.symptomName }}
          </div>
        </div>
      </div>

      <!-- 聊天记录 -->
      <div
          v-for="(msg, index) in chatMessages"
          :key="index"
          class="message"
          :class="msg.type === 'user' ? 'user-message' : 'ai-message'"
      >
        <div class="message-content">{{ msg.content }}</div>
      </div>
    </div>

    <!-- 底部输入区域 -->
    <div class="input-area">
      <div class="input-box">
        <input
            v-model="inputMessage"
            type="text"
            placeholder="描述越细，推荐越准，至少2个字"
            @keyup.enter="sendMessage"
        >
        <div class="send-btn" @click="sendMessage">发送</div>
      </div>

      <!-- 底部功能按钮 -->
      <div class="action-buttons">

      </div>
    </div>
  <div class="chat-container">
    <el-input
        v-model="message"
        placeholder="请输入消息"
        type="textarea"
        :rows="3"
    />
    <el-button type="primary" @click="sendMessage" :loading="loading">发送</el-button>
    <div class="response-area">
      {{ response }}
    </div>
  </div>
  </div>
</template>

<script>
import { querySymptomList } from "@/api/symptom/symptom.js";

export default {
  name: 'ChatComponent',
  props: {
    symptom: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      inputMessage: '',
      message: '',
      response: '',
      quickReplyTags: [],
      chatMessages: [],
      loading: false,
      eventSource: null
    }
  },
  created() {
    this.getQuickReplyTags()
  },
  methods: {
    // 选择快速回复
    async selectQuickReply(tag) {
      this.message = tag
      this.inputMessage = tag
      await this.sendMessage()
    },
    async getQuickReplyTags() {
      try {
        let partId =this.$route.query.partId;

        // 从后端获取快速回复标签
        querySymptomList(partId).then(res => {
          console.log("返回的数据: ",res)
          this.quickReplyTags = res
        })
      } catch (error) {
        console.error('获取快速回复标签失败：', error)
      }
    },
    // 返回上一页
    goBack() {
      console.log('返回按钮')
      this.$router.back()
    },
    sendMessage() {
      if (!this.message.trim()) {
        this.$message.warning('请输入消息');
        return;
      }

      this.loading = true;
      this.response = '';

      // 关闭之前的连接
      if (this.eventSource) {
        this.eventSource.close();
      }

      // 创建SSE连接
      this.eventSource = new EventSource(`/dev-api/ai/ai/chat?message=${encodeURIComponent(this.message)}`);

      this.eventSource.onmessage = (event) => {
        if (event.data === '[complete]') {
          this.loading = false;
          // 如果消息包含挂号成功，并且是消息结束时，才触发支付流程
          // if (this.message.content.includes('挂号成功')) {
          //   // 从消息中提取医生信息
          //   const doctorMatch = this.message.content.match(/医生(\S+)挂号成功/);
          //   const priceMatch = this.message.content.match(/(\d+)元/);
          //
          //   const doctorName = doctorMatch ? doctorMatch[1] : '医生姓名';
          //   const totalPrice = priceMatch ? priceMatch[1] : '100';
          //
          //   // 弹出支付确认框
          //   this.$confirm('挂号成功请考虑清楚在支付！', '提示', {
          //     confirmButtonText: '刷给我狠狠的刷',
          //     cancelButtonText: '认清自己',
          //     type: 'warning'
          //   }).then(() => {
          //     const traceNo = Math.floor(Math.random() * 900000) + 100000;
          //     window.open(
          //         `http://127.0.0.1:9201/pay/pay?subject=${doctorName}&traceNo=${traceNo}&totalAmount=${totalPrice}`,
          //         '_self'
          //     );
          //   }).catch(() => {
          //     this.$message({
          //       type: 'info',
          //       message: '已取消支付'
          //     });
          //   });
          // }
          this.eventSource.close();
        } else {
          this.response += event.data;
        }
      };

      this.eventSource.onerror = (error) => {
        this.loading = false;
        this.eventSource.close();
        this.$message.error('连接出错，请重试');
        console.error('SSE Error:', error);
      };
    }
  },
  beforeDestroy() {
    // 组件销毁前关闭SSE连接
    if (this.eventSource) {
      this.eventSource.close();
    }
  }
}
</script>

<style scoped>
.chat-container {
  padding: 20px;
}
.response-area {
  margin-top: 20px;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 100px;
  white-space: pre-wrap;
}

.ai-chat {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;

  .header {
    height: 44px;
    background-color: #4a90e2;
    color: white;
    display: flex;
    align-items: center;
    padding: 0 16px;
    position: relative;

    .back {
      font-size: 20px;
      padding: 8px;
      margin-left: -8px;
    }

    .title {
      flex: 1;
      text-align: center;
      font-size: 18px;
    }

    .notification {
      padding: 8px;
      margin-right: -8px;
    }
  }

  .chat-container {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    background-color: #f5f5f5;

    .message {
      margin-bottom: 16px;

      .message-content {
        max-width: 70%;
        padding: 12px 16px;
        border-radius: 16px;
        font-size: 14px;
        line-height: 1.5;
      }
    }

    .ai-message {
      .message-content {
        background-color: white;
        margin-right: auto;
      }
    }

    .user-message {
      display: flex;
      justify-content: flex-end;

      .message-content {
        background-color: #4a90e2;
        color: white;
      }
    }
  }

  .quick-replies {
    margin: 20px 0;

    .quick-reply-hint {
      color: #666;
      font-size: 14px;
      margin-bottom: 12px;
    }

    .tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .tag-item {
        background-color: white;
        padding: 8px 16px;
        border-radius: 20px;
        font-size: 14px;
        color: #4a90e2;
        border: 1px solid #4a90e2;
        cursor: pointer;

        &:active {
          opacity: 0.8;
        }
      }
    }
  }

  .input-area {
    background-color: white;
    padding: 12px 16px;
    border-top: 1px solid #eee;

    .input-box {
      display: flex;
      align-items: center;
      background-color: #f5f5f5;
      border-radius: 4px;
      padding: 8px 12px;
      margin-bottom: 12px;

      input {
        flex: 1;
        border: none;
        background: none;
        font-size: 14px;
        padding: 0;
        margin: 0;
        outline: none;

        &::placeholder {
          color: #999;
        }
      }

      .send-btn {
        color: #4a90e2;
        font-size: 14px;
        padding: 4px 8px;
        cursor: pointer;

        &:active {
          opacity: 0.8;
        }
      }
    }

    .quick-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }

    .action-buttons {
      display: flex;
      justify-content: space-around;

      .action-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        font-size: 12px;
        color: #666;
        cursor: pointer;



        &:active {
          opacity: 0.8;
        }
      }
    }
  }

  .doctor-list {
    margin: 20px 0;
    padding: 16px;
    background-color: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .doctor-list-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
      margin-bottom: 16px;
    }

    .doctor-cards {
      display: flex;
      flex-direction: column;
      gap: 16px;
    }

    .doctor-card {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px;
      background-color: #f8f9fa;
      border-radius: 8px;
      border: 1px solid #eee;

      .doctor-info {
        flex: 1;

        .doctor-name {
          font-size: 16px;
          font-weight: bold;
          color: #333;
          margin-bottom: 4px;
        }

        .doctor-title {
          font-size: 14px;
          color: #666;
          margin-bottom: 4px;
        }

        .doctor-specialty {
          font-size: 14px;
          color: #4a90e2;
        }
      }

      .doctor-action {
        margin-left: 16px;

        .consult-btn {
          padding: 8px 16px;
          background-color: #4a90e2;
          color: white;
          border: none;
          border-radius: 20px;
          font-size: 14px;
          cursor: pointer;
          transition: all 0.3s ease;

          &:hover {
            background-color: #357abd;
          }
        }
      }
    }
  }
}
</style>
